package com.shiwaixiangcun.customer.module.intelligent

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.DialogInterface
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v4.app.ActivityCompat
import android.util.Log
import android.view.View
import com.google.gson.reflect.TypeToken
import com.lechange.opensdk.api.bean.DeviceOnline
import com.lechange.opensdk.configwifi.LCOpenSDK_ConfigWifi
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.DeviceBaseEntity
import com.shiwaixiangcun.customer.module.intelligent.camerautil.Business
import com.shiwaixiangcun.customer.module.intelligent.camerautil.ProgressDialog
import com.shiwaixiangcun.customer.network.ResponseConfig
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.JsonUtil
import kotlinx.android.synthetic.main.activity_begin_config.*
import kotlinx.android.synthetic.main.top_bar_white.*


/**
 * 配置摄像头
 */
class ConfigCameraActivity : BaseActivity(), View.OnClickListener {
    var builder: AlertDialog.Builder? = null
    private val startPolling = 0x10
    private val successOnline = 0x11
    private val ansyWaitOnlineTimeOut = 0x12
    private val successAddDevice = 0x13
    private val PROGRESS_TIMEOUT_TIME = 60 * 1000

    private var mProgressDialog: ProgressDialog? = null
    private var isOffline = true

//    private var configView: DiffuseView? = null

    private enum class ConfigStatus {
        query, wifipair, wired
    }

    private var time = 25
    private var mConfigStatus = ConfigStatus.query //默认为轮询状态
    override fun onClick(p0: View?) {
        when (p0) {
            back_left -> {
                finish()
            }
            btn_complete -> {
                readyGoThenKill(IntelligentDeviceActivity::class.java)

            }
        }
    }

    /**
     * 显示对话框
     */
    private fun showDialog(string: String) {

        val dialogOnClickListener = DialogInterface.OnClickListener { dialog, which ->
            when (which) {
                Dialog.BUTTON_POSITIVE -> startConfig()
                Dialog.BUTTON_NEGATIVE -> {
                    finish()
                }
                Dialog.BUTTON_NEUTRAL -> {
                }
            }
        }
        //dialog参数设置
        val builder = AlertDialog.Builder(this)  //先得到构造器
        builder.setTitle("提示") //设置标题
        builder.setMessage(string) //设置内容
        builder.setPositiveButton("确认", dialogOnClickListener)
        builder.setNegativeButton("取消", dialogOnClickListener)


        builder.create().show()
    }

    private var cameraId: String? = null
    private var cameraName: String? = null
    private var wifiName: String? = null
    private var wifiPwd: String? = null
    private var mHandler: Handler? = null
    private var checkOnlineHandler: Handler? = null
    private var cameraRc: String? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_begin_config)
        initBundleData()
        initViewAndEvent()
    }

    /**
     * 获取传递过来的数据
     */
    private fun initBundleData() {
        val extras = intent.extras
        cameraId = extras.getString("camera_id")
        cameraName = extras.getString("camera_name")
        wifiName = extras.getString("wifi_name")
        wifiPwd = extras.getString("wifi_pwd")
        cameraRc = extras.getString("camera_rc")
    }

    @SuppressLint("HandlerLeak")
    private fun initViewAndEvent() {

        mProgressDialog = findViewById(R.id.query_load)

        mHandler = object : Handler() {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                Log.e(BUG_TAG, "msg.what" + msg.what)
                when (msg.what) {
                //无线配对消息回调
                    LCOpenSDK_ConfigWifi.ConfigWifi_Event_Success -> {
                        if (isOffline) {
                            Log.e(BUG_TAG, "无线配对...")
                            mConfigStatus = ConfigStatus.wifipair
                            showToastShort(" 配置网络成功")
                            stopConfig()
                            mHandler?.removeCallbacks(progressPoll)
                            checkDeviceOnline()
                        }
                    }

                    startPolling -> {
                        checkDeviceOnline()
                    }
                    ansyWaitOnlineTimeOut -> {

                        Log.e(BUG_TAG, "checkIsOnlineTimeOut")
                    }
                    successOnline -> {
                        Log.e(BUG_TAG, "successOnline")
                        bindDevice()
                    }

                    successAddDevice -> {
                        Log.e(BUG_TAG, "SuccessAddDevice")
                        showToastShort("添加设备成功")
                        config_view.stop()
                        btn_complete.visibility = View.VISIBLE
                        config_view.visibility = View.GONE


//                        //只有这么一种情况
                        setResult(Activity.RESULT_OK)
//                        finish()
                    }

                }
            }


        }
        checkOnlineHandler = object : Handler() {
            override fun handleMessage(msg: Message) {
                if (!isOffline) return

                val retObject = msg.obj as Business.RetObject
                when (msg.what) {
                    0 -> {
                        if ((retObject.resp as DeviceOnline.Response).data.onLine == "1") {
                            when (mConfigStatus) {
                                ConfigStatus.wired -> Log.e(BUG_TAG, "有线配对....")
                                ConfigStatus.query -> {
                                    Log.e(BUG_TAG, "轮询....")
                                    stopConfig()
//                                    config_view.stop()
//                                    mProgressDialog?.setStop()
                                }
                                ConfigStatus.wifipair -> mProgressDialog?.setStop()
                            }
                            isOffline = false
                            mHandler?.obtainMessage(successOnline)?.sendToTarget()
                        } else {
                            if (mConfigStatus == ConfigStatus.wired) {
                                Log.e(BUG_TAG, "offline..... wired")
                                showToastShort("设备离线")
                            } else if (time > 0) {
                                Log.e(BUG_TAG, "offline..... try again checkOnline")
                                try {
                                    Thread.sleep(2000)
                                } catch (e: InterruptedException) {
                                    e.printStackTrace()
                                }

                                time -= 2
                                mHandler?.obtainMessage(startPolling)?.sendToTarget()
                            } else {
                                Log.e(BUG_TAG, "offline..... try again max")
                                config_view.stop()
                                time = 25
                                showToastShort("设备离线")
//                                showDialog("设备当前状态为离线，是否重新配置?")

                            }
                        }
                    }
                    -1000 -> {
                        if (time > 0) {
                            Log.e(BUG_TAG, "code:-1000..... try again checkOnline")
                            try {
                                Thread.sleep(2000)
                            } catch (e: InterruptedException) {

                                e.printStackTrace()
                            }

                            time--
                            mHandler?.obtainMessage(startPolling)?.sendToTarget()
                        }
                    }
                    else -> {
                        when (mConfigStatus) {
                            ConfigStatus.wired -> Log.e(BUG_TAG, "有线配对失败....")
                            ConfigStatus.query -> {
                                Log.e(BUG_TAG, "轮询失败....")
                                stopConfig()
                                mProgressDialog?.setStop()
                            }
                            ConfigStatus.wifipair -> mProgressDialog?.setStop()
                        }
                        showToastShort(retObject.mMsg)
                    }
                }
            }
        }
        tv_page_name.text = "配置摄像机"
        back_left.setOnClickListener(this)
        btn_complete.setOnClickListener(this)
        config_view?.setOnItemSelectListener {
            config_view?.start()
            startConfig()
        }


    }


    /**
     * 绑定设备
     */
    private fun bindDevice() {
        val strToken = AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_TOKEN, "") as String
        OkGo.post<String>(GlobalApi.bindCamera)
                .params("access_token", strToken)
                .params("code", cameraRc)
                .params("deviceId", cameraId)
                .params("name", cameraName)
                .params("wifi", wifiName)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        Log.e(BUG_TAG, response?.body().toString())
                        val type = object : TypeToken<DeviceBaseEntity<Any>>() {}.type
                        val fromJson = JsonUtil.fromJson<DeviceBaseEntity<Any>>(response?.body(), type)
                        when (fromJson.responseCode) {
                            ResponseConfig.SUCCESS -> {


                                mHandler?.obtainMessage(successAddDevice)?.sendToTarget()

                            }

                        }
                    }

                })

    }

    /**
     * 检查设备是否在线
     */
    private fun checkDeviceOnline() {
        Business.getInstance().checkOnline(cameraId, checkOnlineHandler)
    }

    override fun onPause() {
        super.onPause()
        stopConfig()

    }


    /**
     * 开始无线Wifi配置
     */
    private fun startConfig() {
        config_view.start()
//        //无线超时任务
        mHandler?.postDelayed(progressRun, PROGRESS_TIMEOUT_TIME.toLong())
        //10s开启轮询
        mHandler?.postDelayed(progressPoll, (10 * 1000).toLong())
        LCOpenSDK_ConfigWifi.configWifiStart(cameraId, wifiName, wifiPwd, "", mHandler)
    }


    override fun onDestroy() {
        mHandler?.removeCallbacksAndMessages(null)
        checkOnlineHandler?.removeCallbacksAndMessages(null)
        mHandler?.removeCallbacks(progressRun)
        mHandler?.removeCallbacks(progressPoll)
        super.onDestroy()
    }
    /**
     * 无线配对超时任务
     */
    private val progressRun = Runnable {

        //        showToastShort("超时配置失败")
        stopConfig()
    }

    /**
     * 轮询定时启动任务
     */
    private val progressPoll = Runnable {
        mHandler?.obtainMessage(startPolling)?.sendToTarget()
    }

    /**
     * 停止Wifi配置
     */
    private fun stopConfig() {

        LCOpenSDK_ConfigWifi.configWifiStop()//调用smartConfig停止接口
    }

    /**
     * 开启无线配网流程（权限检查，配对说明）
     */
    private fun configCamera() {
        val isMinSDKM = Build.VERSION.SDK_INT < 23
        val isGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
        if (isMinSDKM || isGranted) {

            startConfig()
            //开启无线配对
            return
        }

        //		requestLocationPermission();
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
                                            grantResults: IntArray) {
        if (grantResults.size == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Camera permission has been granted, preview can be displayed
            startConfig()

        } else {
            showToastShort("位置服务已被禁止，请在《权限管理》打开")


        }

    }


}
